package com.ybt.context.util;


import java.io.Serializable;
import java.util.Iterator;
import java.util.Properties;

import com.ruleengine.context.EContextPropertyScope;
import com.ruleengine.context.IContextProperty;
import com.ruleengine.context.IWorkflowConext;
import com.ruleengine.context.impl.ContextPropertyFactory;
import com.ybt.router.core.message.IMSDMessage;

public class ContextUtil {
    /**
     * 将消息中的可序列化属性拷贝到target中
     * @param source
     * @return
     */
    public static Properties getSeriPropertys(IWorkflowConext source){
        Properties target = new Properties();
        Iterator<IContextProperty<?>> it = source.propertyIterator();
        while(it.hasNext()){
            IContextProperty<?> p = it.next();
            if(p.getScope()==EContextPropertyScope.PRIVATE){
                continue;
            }
            Object o = p.getValue();
            if(o instanceof Serializable){
                target.put(p.getKey(), p.getValue());
            }
        }
        return target;
    }
    
    /**
     * 将context转换成消息
     * @param msg
     * @return
     */
    public static void copyPropertys(IWorkflowConext context, IMSDMessage<byte[]> msg){
        Properties src = msg.getHeader();
        Iterator it = src.keySet().iterator();
        while(it.hasNext()){
            String key = (String)it.next();
            Object value = src.get(key);
            
            IContextProperty<Object> pro = ContextPropertyFactory
                    .getInstance().createSerializeVariable(
                            key);
            pro.setValue(value);
            context.setContextProperty(pro);
        }
    }
    
    
}
